package club.justwill.single.Controller;

import club.justwill.single.Service.PayService;
import club.justwill.single.aspect.LoginRequired;
import club.justwill.single.bean.RefundData;
import club.justwill.single.model.CoreConstants;
import club.justwill.single.model.JsonResponse;
import club.justwill.single.model.SecurityToken;
import club.justwill.single.util.AlipayNotify;
import club.justwill.single.util.JsonResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static club.justwill.single.helper.PayHelper.verifyResult;

/**
 * Created by xiangnan on 16-2-2.
 */
@RestController
@Scope(WebApplicationContext.SCOPE_SESSION)
public class PayforController extends BaseController {

    @Autowired
    private PayService payService;

    @RequestMapping(value = URL_PAY_WEICHAT, method = RequestMethod.POST, produces = CoreConstants.MIME_JSON)
    public @ResponseBody JsonResponse weiChatPay(@PathVariable Long orderId) {
        JsonResponse obj = new JsonResponse();
        SecurityToken token = new SecurityToken(sessionState.getUserId());
        token.generateToken(sessionState);
        String html = payService.payOrderByWeiChat(orderId, token, obj);
        if(JsonResponseHelper.isHasError(obj)) {
            obj.setFailed();
        } else {
            obj.setData(html);
            obj.setSuccessful();
        }
        return obj;
    }

    @RequestMapping(value = URL_PAY_APP, method = RequestMethod.POST, produces = CoreConstants.MIME_JSON)
    public JsonResponse appPay(@PathVariable Long orderId) {
        JsonResponse obj = new JsonResponse();
        SecurityToken token = new SecurityToken(sessionState.getUserId());
        token.generateToken(sessionState);
        Map<String,String> signedParam = payService.signParam(obj, token, orderId);
        if(JsonResponseHelper.isHasError(obj)) {
            obj.setFailed();
        } else {
            obj.setData(signedParam);
            obj.setSuccessful();
        }
        return obj;
    }

    @RequestMapping(value = URL_PAY_REFRESH , produces = CoreConstants.MIME_JSON)
    public void refreshOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/xml;charset=UTF-8");
        SecurityToken token = new SecurityToken(sessionState.getUserId());
        token.generateToken(sessionState);
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        if(verifyResult(request)) {
            if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                Boolean status = payService.refreshOrder(Long.parseLong(out_trade_no), token, trade_no);
                if(status) {
                    response.getWriter().println("success");
                } else {
                    response.getWriter().println("fail");
                }
            }

        } else {
            response.getWriter().println("fail");
        }
    }

    @RequestMapping(value = URL_PAY_RETURN, method = RequestMethod.GET)
    public void returnPay(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        if(verifyResult(request)) {
            if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
            }
            response.getWriter().println("验证成功<br />");
        }else{
            response.getWriter().println("验证失败");
        }
    }

    @LoginRequired
    @RequestMapping(value = URL_REFUND, method = RequestMethod.POST,produces = CoreConstants.MIME_JSON)
    public JsonResponse refund(@RequestBody RefundData refundData){
        JsonResponse obj = new JsonResponse();
        SecurityToken token = new SecurityToken(sessionState.getUserId());
        token.generateToken(sessionState);
        String data = payService.refundByProject(token,refundData,obj);
        if(JsonResponseHelper.isHasError(obj)) {
            obj.setFailed();
        } else {
            obj.setData(data);
            obj.setSuccessful();
        }
        return obj;
    }

    @RequestMapping(value = URL_REFUND_NOTIFY, method = RequestMethod.POST)
    public void returnRefund(HttpServletRequest request,HttpServletResponse response) throws IOException {
        JsonResponse obj = new JsonResponse();
        SecurityToken token = new SecurityToken(sessionState.getUserId());
        token.generateToken(sessionState);
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //批次号
        String batch_no = new String(request.getParameter("batch_no").getBytes("ISO-8859-1"),"UTF-8");

        //批量退款数据中转账成功的笔数

        String success_num = new String(request.getParameter("success_num").getBytes("ISO-8859-1"),"UTF-8");

        //批量退款数据中的详细信息
        String result_details = new String(request.getParameter("result_details").getBytes("ISO-8859-1"),"UTF-8");

        if(AlipayNotify.verify(params)){
            //退款回调
            payService.returnRefund(token,obj,batch_no);
            if(JsonResponseHelper.isHasError(obj)) {
                obj.setFailed();
            } else {
                obj.setSuccessful();
            }
            out.println("success");
        }else{
            out.println("fail");
        }
    }
}
